#include "face_detect.h"

#define LOG_TAG "face_detect.cpp"
#include "utils.h"

static CvMemStorage *storage = cvCreateMemStorage(0);

bool face_detect( IplImage* srcImg, CvHaarClassifierCascade* cascade, CvRect *faceRect)
{

    // Create two points to represent the face locations
    CvPoint pt1, pt2;
    int i;

    if( !cascade )
    {
        LOGE("%s: faceCascade is NULL", __FILE__);
        return false;
    }
    
    if(faceRect == NULL) {
        LOGE("%s: passed face rectange is NULL", __FILE__);
        return false;
    }
    

    // Clear the memory storage which was used before
    cvClearMemStorage( storage );

    int max_width = 0;
    // Find whether the cascade is loaded, to find the biggest face. If yes, then:
    if( cascade )
    {

        // There can be more than one face in an image. So create a growable sequence of faces.
        // Detect the objects and store them in the sequence

//DURATION_START
        CvSeq* faces = cvHaarDetectObjects( srcImg, cascade, storage,
                                            1.3, 2, CV_HAAR_DO_CANNY_PRUNING,
                                            cvSize(10, 10) );
//DURATION_STOP("haardetect()")

        // Loop the number of faces found.
        for( i = 0, max_width=0; i < faces->total; i++ )
        {
           // Create a new rectangle for the face
            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );

            if(max_width < r->width) {

                faceRect->x = pt1.x = r->x;
                faceRect->y = pt1.y = r->y;
                faceRect->width = r->width;
                faceRect->height = r->height;

                pt2.x = (r->x + r->width);
                pt2.y = (r->y + r->height);
                max_width = r->width;
        
                //printf("%s: found face width: %d\n", __func__, max_width);
                // __android_log_print(ANDROID_LOG_DEBUG, "face_detect.cpp", "[%d] face_width = %d", __LINE__, max_width);
            }

        }

        if(max_width <= 4) {
            memset(faceRect, 0, sizeof(CvRect));
            return false;
        }

        // Draw the rectangle in the input image
        //cvRectangle( srcImg, pt1, pt2, CV_RGB(255,0,0), 3, 8, 0 );

        return true;

    }

    return false;
}
